package com.infore.qualityControl.export.util;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.infore.qualityControl.enums.ExportTableEnum;
import com.infore.qualityControl.po.IntegratedIntervention;
import com.infore.qualityControl.po.RealWaterSampleComparison;
import com.infore.qualityControl.util.ArrayUtils;
import com.infore.qualityControl.util.MyBeanUtils;
import com.infore.qualityControl.util.ResultEntity;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.rtf.RtfWriter2;
/**
 * 导出excel、pdf、word工具类
 * @author Cold
 *
 */
public class ExportUtil {
	
	@SuppressWarnings("unused")
	private final static Logger logger = LoggerFactory.getLogger(ExportUtil.class);
	private final static String[] parsePatterns = {"yyyy-MM-dd",
            "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
            "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyyMMdd"};
	
	/******************************* 导出excel **************************/
	
    /**
     * 获取头内容
     * 
     * @param headers
     * @param sheet
     * @param style
     * @param row
     */
    private static void getTrendsHeader(List<List<JSONObject>> table, HSSFSheet sheet, CellStyle style, HSSFRow row, int maxCol) {
    	for (int i = 0; i < table.size(); i++) {
			row = sheet.createRow(i + 1);
			row.setHeight((short) 700);
			//表格每行的按照最大列数进行创建
			for (int k = 0; k < maxCol; k++) {
				row.createCell(k).setCellStyle(style);
			}
			for (int j = 0; j < table.get(i).size() - 1; j++) {
			    int col1 = Integer.parseInt(table.get(i).get(j).get("col").toString());          //单元格列绝对位置
				int row2 = Integer.parseInt(table.get(i).get(j).get("row").toString());      //单元格行绝对位置
				int colspan = Integer.parseInt(table.get(i).get(j).get("colspan").toString());   //合并列
				int rowspan = Integer.parseInt(table.get(i).get(j).get("rowspan").toString()); //合并行
				String val = table.get(i).get(j).get("val").toString(); // 文本值
				//根据单元格的绝对位置坐标进行合并
				if(rowspan > 0 || colspan > 0){
					sheet.addMergedRegion(new CellRangeAddress(row2 + 1, row2 + rowspan + 1, col1, col1 + colspan)); //四个坐标按顺序分别表示：起始行、结束行、起始列、结束列
				}
				HSSFCell cell = null;
				cell = row.getCell(col1);  //获取单元格
				cell.setCellStyle(style); //单元格样式设置
				cell.setCellValue(val); //单元格值设置
			}
		}
    }
    
	/**
     * 生成头样式
     * 
     * @param workbook
     * @return
     */
    private static HSSFCellStyle headStyle(HSSFWorkbook workbook) {
        HSSFCellStyle headerStyle = workbook.createCellStyle();
        // 设置这些样式
        Font headerFont = workbook.createFont();
		headerFont.setFontName("微软雅黑");
		headerFont.setFontHeightInPoints((short) 14);
		headerFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
		headerFont.setColor(HSSFColor.BLACK.index);
		
		headerStyle.setFont(headerFont);
		headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 左右居中
		headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
		headerStyle.setLocked(true);
		headerStyle.setWrapText(false);// 自动换行
		
		headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  // 填充单元格
		headerStyle.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index); // 设置表头的背景颜色
        return headerStyle;
    }
    
    /**
     * 生成内容样式(上下左右居中)
     * 
     * @param workbook
     * @return
     */
    private static HSSFCellStyle contentStyle(HSSFWorkbook workbook) {
        HSSFCellStyle commonStyle = workbook.createCellStyle();
        
        Font contextFont = workbook.createFont();
		contextFont.setFontName("微软雅黑");
		contextFont.setFontHeightInPoints((short) 10);
		contextFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
		contextFont.setColor(HSSFColor.BLACK.index);
		
		commonStyle.setFont(contextFont);
		commonStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		commonStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
		commonStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
		commonStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
		commonStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
		commonStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
		commonStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		commonStyle.setLocked(true);
		commonStyle.setWrapText(true);// 先设置为自动换行
		commonStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  //填充单元格
		commonStyle.setFillForegroundColor(HSSFColor.WHITE.index); 
        
        return commonStyle;
    }
    
    /**
     * 生成内容样式(上下居中、居左)
     * 
     * @param workbook
     * @return
     */
    private static HSSFCellStyle contentLeftStyle(HSSFWorkbook workbook) {
        HSSFCellStyle commonStyle = workbook.createCellStyle();
        
        Font contextFont = workbook.createFont();
		contextFont.setFontName("微软雅黑");
		contextFont.setFontHeightInPoints((short) 10);
		contextFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
		contextFont.setColor(HSSFColor.BLACK.index);
		
		commonStyle.setFont(contextFont);
		commonStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		commonStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
		commonStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
		commonStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
		commonStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
		commonStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 居左
		commonStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		commonStyle.setLocked(true);
		commonStyle.setWrapText(true);// 先设置为自动换行
		commonStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  //填充单元格
		commonStyle.setFillForegroundColor(HSSFColor.WHITE.index); 
        
        return commonStyle;
    }
	
	/**
     * 创建一行且单元格以最大列数合并，内容居中，字体设置开关.
     * 
     * @param row 第n行 设置(n-1)
     * @param content 单元格内容
     * @param sheet 工作页
     * @param workbook 工作簿
     * @param maxcol 最大列数
     * @param flag 是否设置字体样式 true：设置字体20px，加粗
     */
    public static void createCell(int row, String content, HSSFSheet sheet, HSSFWorkbook workbook, int maxcol, boolean flag) {
        HSSFRow titleRow = sheet.createRow(row);
        titleRow.setHeight((short) ((35 * 15.625)));
        HSSFCellStyle titleStyle = workbook.createCellStyle();
        // 设置内容垂直居中、水平居中
//        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  //填充单元格
        titleStyle.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index); 
        for (int k = 0; k < maxcol; k++) {
        	titleRow.createCell(k).setCellStyle(titleStyle);
        }
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(row, row, 0, maxcol - 1));
        HSSFCell cell = titleRow.getCell(0);
        cell.setCellValue(content);
        if (flag) {
            // 设置字体大小、加粗
            HSSFFont font = workbook.createFont();
            font.setFontHeightInPoints((short) 20);
            font.setBoldweight((short) 10);
            titleStyle.setFont(font);
        }
    }
    
	/**
	* @Title: exportExcel
	* @Description: 导出单个表格数据
	* @param request
	* @param list 表内容数据
	* @param headerProp 表的映射字段
	* @param pattern 时间格式
	* @return    参数
	* @return byte[]    返回类型
	* @throws
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	public static byte[] exportExcel(HttpServletRequest request, List<Map<String, Object>> list, String headerProp, String pattern){
		String tableData = request.getParameter("tableData");
		JSONObject json = JSONObject.parseObject(tableData);
		List<List<JSONObject>> headTableData = (List<List<JSONObject>>) json.get("data"); //获取表头数据
		
		int maxcol = Integer.parseInt(json.get("maxcol").toString());  //获取最大列数
		String fileName = json.get("name").toString();  //表名
		
		HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(fileName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
		
        // 生成表头样式
        CellStyle headStyle = headStyle(workbook);
        // 生成并设置另一个样式
        CellStyle contentStyle = contentStyle(workbook);
        // 声明一个画图的顶级管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        int rowCount = 0;
        if (StringUtils.isNotBlank(fileName)) {
            createCell(rowCount, fileName, sheet, workbook, maxcol, true);
            rowCount++;
        }
        // 产生表格标题行
        HSSFRow row = sheet.createRow(rowCount);
        // 获得头内容
        getTrendsHeader(headTableData, sheet, headStyle, row, maxcol);
        // 表头内容信息获取完之后 将行数设置为表头的最大行数,因为有标题,行数需要加1
        rowCount = headTableData.size() + 1;
        
        // 获取映射对应的字段名
        List<String> fieldPropertyList = ArrayUtils.stringToList(headerProp);
        // 遍历集合数据，产生数据行
        for (int index = 0; index < list.size(); index++) {
            row = sheet.createRow(rowCount++);
            row.setHeight((short) 500);
            Map<String, Object> map = list.get(index);
            // 频繁反射影响性能，使用map字段匹配
            for (int i = 0; i <= fieldPropertyList.size(); i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(contentStyle);
                // 判断值的类型后进行强制类型转换
                Object value = null;
                String textValue = null;
                if (i == 0) {
                	value = (index + 1) + "";
                } else {
                	String fieldName = fieldPropertyList.get(i - 1);
                	value = map.get(fieldName.replaceAll("\"", ""));
                }
                if (value instanceof Boolean) {
                    boolean bValue = (Boolean) value;
                    textValue = "是";
                    if (!bValue) {
                        textValue = "不是";
                    }
                } else if (value instanceof Date) {
                    Date date = (Date) value;
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    textValue = sdf.format(date);
                } else if (value instanceof byte[]) {
                    // 有图片时，设置行高为60px;
                    row.setHeightInPoints(60);
                    // 设置图片所在列宽度为80px,注意这里单位的一个换算
                    sheet.setColumnWidth(i, (short) (35 * 80));
                    // sheet.autoSizeColumn(i);
                    byte[] bsValue = (byte[]) value;
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);
                    anchor.setAnchorType(2);
                    patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                } else if (value != null) {
                    // 其它数据类型都当作字符串简单处理
                	if (parseDate(value.toString())) { // 判断字符串是否为时间格式
                    	SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    	Date date = null;
    					try {
    						date = sdf.parse(value.toString());
    					} catch (ParseException e) {
    						e.printStackTrace();
    					}
                    	textValue = sdf.format(date);
                    } else {
                    	textValue = value.toString();
                    }
                }
                // 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
                if (textValue != null) {
                    Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                    Matcher matcher = p.matcher(textValue);
                    if (matcher.matches() || (value instanceof Double)) {
                        // 是数字当作double处理
                        cell.setCellValue(Double.parseDouble(textValue));
                    } else {
                        HSSFRichTextString richString = new HSSFRichTextString(textValue);
                        cell.setCellValue(richString);
                    }
                }
            }
        }
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		byte[] bytes = null;
        try {
        	workbook.write(os);
        	bytes = os.toByteArray();
            os.close(); 
        } catch (IOException e) {
            e.printStackTrace();
        }
		return bytes;
	}
	
	/**
	* @Title: exportExcel
	* @Description: 导出单个表格数据(特殊表格)
	* @param request
	* @param list 表内容数据
	* @param headerProp 表的映射字段
	* @param pattern 时间格式
	* @return    参数
	* @return byte[]    返回类型
	* @throws
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	public static byte[] exportSpecialExcel(HttpServletRequest request,
			String headerProp, String pattern, String tableType, ResultEntity resultEntity) throws Exception {
		String tableData = request.getParameter("tableData");
		JSONObject json = JSONObject.parseObject(tableData);
		List<List<JSONObject>> headTableData = (List<List<JSONObject>>) json.get("data"); // 获取表头数据

		int maxcol = Integer.parseInt(json.get("maxcol").toString()); // 获取最大列数
		String fileName = json.get("name").toString(); // 表名

		HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(fileName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 20);
		
        // 生成表头样式
        CellStyle headStyle = headStyle(workbook);
        // 生成并设置另一个样式
        CellStyle contentStyle = contentStyle(workbook);
        // 声明一个画图的顶级管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        int rowCount = 0;
        if (StringUtils.isNotBlank(fileName)) {
            createCell(rowCount, fileName, sheet, workbook, maxcol, true);
            rowCount++;
        }
        // 产生表格标题行
        HSSFRow row = sheet.createRow(rowCount);
        // 获得头内容
        getTrendsHeader(headTableData, sheet, headStyle, row, maxcol);
        // 表头内容信息获取完之后 将行数设置为表头的最大行数,因为有标题,行数需要加1
        rowCount = headTableData.size() + 1;
        // 获取映射对应的字段名
        List<String> fieldPropertyList = ArrayUtils.stringToList(headerProp);
        // 作特殊处理
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        List<Object> dataList = (List<Object>) ((Map<String, Object>) resultEntity.getContent()).get("dataList"); // 获取数据集
		for (int j = 0; j < dataList.size(); j++) {
			Map<String, Object> dataMap = (Map<String, Object>) dataList.get(j);
			Map<String, Object> timeMap = new HashMap<String, Object>();
			list = new ArrayList<Map<String, Object>>();
			if (tableType.equals(ExportTableEnum.REAL_WATER_DATA.getCode())) {
				List<RealWaterSampleComparison> realWaterSampleComparisonList = (List<RealWaterSampleComparison>) dataMap.get("list");
				String samplingTime = dataMap.get("time").toString(); // 采样时间
				timeMap.put("time", samplingTime);
				for (RealWaterSampleComparison realWaterSampleComparison : realWaterSampleComparisonList) {
					list.add(MyBeanUtils.convertBeanToMap(realWaterSampleComparison, pattern));
				}
			} else if (tableType.equals(ExportTableEnum.INTEGRATED_INTERVENTION_DATA.getCode())) {
				List<IntegratedIntervention> integratedInterventionList = (List<IntegratedIntervention>) dataMap.get("list");
				String artificiaSamplingTime = dataMap.get("artificiaSamplingTime").toString(); // 人工采样时间
				String automaticSamplingTime = dataMap.get("automaticSamplingTime").toString(); // 自动取样时间
				timeMap.put("artificiaSamplingTime", artificiaSamplingTime);
				timeMap.put("automaticSamplingTime", automaticSamplingTime);
				for (IntegratedIntervention integratedIntervention : integratedInterventionList) {
					list.add(MyBeanUtils.convertBeanToMap(integratedIntervention, pattern));
				}
			}
			CellStyle contentLeftStyle = contentLeftStyle(workbook);
			row = sheet.createRow(rowCount++);
			row.setHeight((short) 500);
			for (int k = 0; k < maxcol; k++) {
				row.createCell(k).setCellStyle(contentLeftStyle);
			}
			// 合并单元格
			sheet.addMergedRegion(new CellRangeAddress(rowCount - 1, rowCount - 1, 0, maxcol - 1));
			if (tableType.equals(ExportTableEnum.REAL_WATER_DATA.getCode())) {
				row.getCell(0).setCellValue("采样时间：" + timeMap.get("time"));
			} else if (tableType.equals(ExportTableEnum.INTEGRATED_INTERVENTION_DATA.getCode())) {
				row.getCell(0).setCellValue("自动取样时间：" + timeMap.get("automaticSamplingTime") + ", 人工采样时间："
						+ timeMap.get("artificiaSamplingTime"));
			}
			// 遍历集合数据，产生数据行
			for (int index = 0; index < list.size(); index++) {
				row = sheet.createRow(rowCount++);
				row.setHeight((short) 500);
				Map<String, Object> map = list.get(index);
				// 频繁反射影响性能，使用map字段匹配
				for (int i = 0; i <= fieldPropertyList.size(); i++) {
					HSSFCell cell = row.createCell(i);
					cell.setCellStyle(contentStyle);
					// 判断值的类型后进行强制类型转换
					Object value = null;
					String textValue = null;
					if (i == 0) {
						value = (index + 1) + "";
					} else {
						String fieldName = fieldPropertyList.get(i - 1);
						value = map.get(fieldName.replaceAll("\"", ""));
					}
					if (value instanceof Boolean) {
						boolean bValue = (Boolean) value;
						textValue = "是";
						if (!bValue) {
							textValue = "不是";
						}
					} else if (value instanceof Date) {
						Date date = (Date) value;
						SimpleDateFormat sdf = new SimpleDateFormat(pattern);
						textValue = sdf.format(date);
					} else if (value instanceof byte[]) {
						// 有图片时，设置行高为60px;
						row.setHeightInPoints(60);
						// 设置图片所在列宽度为80px,注意这里单位的一个换算
						sheet.setColumnWidth(i, (short) (35 * 80));
						// sheet.autoSizeColumn(i);
						byte[] bsValue = (byte[]) value;
						HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6,
								index);
						anchor.setAnchorType(2);
						patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
					} else if (value != null) {
						// 其它数据类型都当作字符串简单处理
						if (parseDate(value.toString())) { // 判断字符串是否为时间格式
							SimpleDateFormat sdf = new SimpleDateFormat(pattern);
							Date date = null;
							try {
								date = sdf.parse(value.toString());
							} catch (ParseException e) {
								e.printStackTrace();
							}
							textValue = sdf.format(date);
						} else {
							textValue = value.toString();
						}
					}
					// 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
					if (textValue != null) {
						Pattern p = Pattern.compile("^//d+(//.//d+)?$");
						Matcher matcher = p.matcher(textValue);
						if (matcher.matches() || (value instanceof Double)) {
							// 是数字当作double处理
							cell.setCellValue(Double.parseDouble(textValue));
						} else {
							HSSFRichTextString richString = new HSSFRichTextString(textValue);
							cell.setCellValue(richString);
						}
					}
				}
			}
		}
        
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		byte[] bytes = null;
        try {
        	workbook.write(os);
        	bytes = os.toByteArray();
            os.close(); 
        } catch (IOException e) {
            e.printStackTrace();
        }
		return bytes;
	}
	
	/******************************* 导出pdf **************************/
	
	/**
     * 获取pdf头内容
     * 
     * @param headers
     * @param sheet
     * @param style
     * @param row
     */
    private static void getPdfTrendsHeader(List<List<JSONObject>> table, PdfPTable pdfPTable, PdfPCell pdfPCell, com.lowagie.text.Font font, int maxCol) {
        for (int i = 0; i < table.size(); i++) {
            for (int j = 0; j < table.get(i).size() - 1; j++) {
                int colspan = Integer.parseInt(table.get(i).get(j).get("colspan").toString()) + 1; // 合并列
                int rowspan = Integer.parseInt(table.get(i).get(j).get("rowspan").toString()) + 1; // 合并行
                String val = table.get(i).get(j).get("val").toString(); // 文本值
                pdfPCell.setPhrase(new Paragraph(val, font));
                pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
                pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);  //垂直居中
                pdfPCell.setColspan(colspan);
                pdfPCell.setRowspan(rowspan);
                pdfPTable.addCell(pdfPCell);
            }
        }
    }
    
    /**
     * 生成pdf头样式
     * 
     * @param pdfTableHeaderCell
     * @return
     */
    private static void pdfHeadStyle(PdfPCell pdfTableHeaderCell) {
        pdfTableHeaderCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        pdfTableHeaderCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        pdfTableHeaderCell.setBackgroundColor(new Color(150, 150, 150));
        pdfTableHeaderCell.setBorderColorBottom(new Color(0x674ea7));
        pdfTableHeaderCell.setBorderColorLeft(new Color(0x674ea7));
        pdfTableHeaderCell.setBorderColorRight(new Color(0x674ea7));
        pdfTableHeaderCell.setBorderColorTop(new Color(0x674ea7));
    }
	
	/**
    * @Title: exportPdf
    * @Description: 导出单个表格数据
    * @param request
    * @param list 表内容数据
    * @param headerProp 表的映射字段
    * @param pattern 时间格式
    * @return    参数
    * @return byte[]    返回类型
    * @throws
     */
    @SuppressWarnings({ "unchecked" })
    public static byte[] exportPdf(HttpServletRequest request, List<Map<String, Object>> list, String headerProp, String pattern) throws Exception {
        String tableData = request.getParameter("tableData");
        JSONObject json = JSONObject.parseObject(tableData);
        List<List<JSONObject>> headTableData = (List<List<JSONObject>>) json.get("data"); //获取表头数据
        
        int maxcol = Integer.parseInt(json.get("maxcol").toString());  //获取最大列数
        String fileName = json.get("name").toString();  //表名
        
        // 创建一个文档对象纸张大小为A4
        Document document = new Document(PageSize.A4);
        // 设置要输出到磁盘上的文件名称
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, bos);
        // 打开文档开始写内容
        document.open();
        // 创建一个N列的表格控件  
        PdfPTable pdfPTable = new PdfPTable(maxcol);
        // 设置表格占PDF文档100%宽度
        pdfPTable.setWidthPercentage(100);
        // 中文采用Windows系统字体，幼圆常规字体
        BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);  
        com.lowagie.text.Font titleFont = new com.lowagie.text.Font(baseFont,10,com.lowagie.text.Font.BOLD);
        com.lowagie.text.Font font = new com.lowagie.text.Font(baseFont,8,com.lowagie.text.Font.NORMAL);
        // 创建一个表格的标题  
        PdfPCell pdfCellTitle = new PdfPCell(new Phrase(fileName, titleFont));
        pdfCellTitle.setColspan(maxcol);
        pdfCellTitle.setBorder(PdfPCell.NO_BORDER);
        pdfCellTitle.setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
        pdfCellTitle.setVerticalAlignment(Element.ALIGN_MIDDLE);  //垂直居中
        pdfPTable.addCell(pdfCellTitle);
        // 创建一个表格的表头单元格  
        PdfPCell pdfTableHeaderCell = new PdfPCell();
        // 设置表头样式
        pdfHeadStyle(pdfTableHeaderCell);
        // 获得头内容
        getPdfTrendsHeader(headTableData, pdfPTable, pdfTableHeaderCell, font, maxcol);
        // 获取映射对应的字段名
        List<String> fieldPropertyList = ArrayUtils.stringToList(headerProp);
        // 遍历集合数据，产生数据行
        for (int index = 0; index < list.size(); index++) {
            Map<String, Object> map = list.get(index);
            for (int i = 0; i <= fieldPropertyList.size(); i++) {
                // 判断值的类型后进行强制类型转换
                Object value = null;
                String textValue = null;
                if (i == 0) {
                    value = (index + 1) + "";
                } else {
                    String fieldName = fieldPropertyList.get(i - 1);
                    value = map.get(fieldName.replaceAll("\"", ""));
                }
                if (value instanceof Boolean) {
                    boolean bValue = (Boolean) value;
                    textValue = "是";
                    if (!bValue) {
                        textValue = "不是";
                    }
                } else if (value instanceof Date) {
                    Date date = (Date) value;
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    textValue = sdf.format(date);
                } else if (value instanceof byte[]) {
                    // 有图片时，设置行高为60px;
//                    row.setHeightInPoints(60);
//                    // 设置图片所在列宽度为80px,注意这里单位的一个换算
//                    sheet.setColumnWidth(i, (short) (35 * 80));
//                    // sheet.autoSizeColumn(i);
//                    byte[] bsValue = (byte[]) value;
//                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);
//                    anchor.setAnchorType(2);
//                    patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                } else if (value != null) {
                    // 其它数据类型都当作字符串简单处理
                    if (parseDate(value.toString())) { // 判断字符串是否为时间格式
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        Date date = null;
                        try {
                            date = sdf.parse(value.toString());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        textValue = sdf.format(date);
                    } else {
                        textValue = value.toString();
                    }
                }
                PdfPCell pdfCell = new PdfPCell(new Phrase(textValue, font));
                pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
                pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);  //垂直居中
                pdfPTable.addCell(pdfCell);
            }
        }
        document.add(pdfPTable);
        document.close();
        writer.close();
        
        byte[] bytes = {};
        try {
            bytes = bos.toByteArray();
            bos.close(); 
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }
    
    
    /******************************* 导出word **************************/
    
    /**
     * 获取word头内容
     * 
     * @param headers
     * @param sheet
     * @param style
     * @param row
     */
    private static void getWordTrendsHeader(List<List<JSONObject>> table, Table wordTable, Cell cell, com.lowagie.text.Font font, int maxCol) throws Exception {
        for (int i = 0; i < table.size(); i++) {
            for (int j = 0; j < table.get(i).size() - 1; j++) {
                int colspan = Integer.parseInt(table.get(i).get(j).get("colspan").toString()) + 1; // 合并列
                int rowspan = Integer.parseInt(table.get(i).get(j).get("rowspan").toString()) + 1; // 合并行
                String val = table.get(i).get(j).get("val").toString(); // 文本值
                cell = new Cell(new Phrase(val,font));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);  //垂直居中
                cell.setColspan(colspan);
                cell.setRowspan(rowspan);
                wordTable.addCell(cell);
            }
        }
    }
    
    /**
     * 生成word头样式
     * 
     * @param wordTableHeaderCell
     * @return
     */
    private static void wordHeadStyle(Cell wordTableHeaderCell) {
        wordTableHeaderCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        wordTableHeaderCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        wordTableHeaderCell.setBackgroundColor(new Color(150, 150, 150));
        wordTableHeaderCell.setBorderColorBottom(new Color(0x674ea7));
        wordTableHeaderCell.setBorderColorLeft(new Color(0x674ea7));
        wordTableHeaderCell.setBorderColorRight(new Color(0x674ea7));
        wordTableHeaderCell.setBorderColorTop(new Color(0x674ea7));
    }
    
    /**
     * @Title: exportWord
     * @Description: 导出单个表格数据
     * @param request
     * @param list 表内容数据
     * @param headerProp 表的映射字段
     * @param pattern 时间格式
     * @return    参数
     * @return byte[]    返回类型
     * @throws
      */
     @SuppressWarnings({ "unchecked" })
     public static byte[] exportWord(HttpServletRequest request, List<Map<String, Object>> list, String headerProp, String pattern) throws Exception {
         String tableData = request.getParameter("tableData");
         JSONObject json = JSONObject.parseObject(tableData);
         List<List<JSONObject>> headTableData = (List<List<JSONObject>>) json.get("data"); //获取表头数据
         
         int maxcol = Integer.parseInt(json.get("maxcol").toString());  //获取最大列数
         String fileName = json.get("name").toString();  //表名
         
         // 创建一个文档对象纸张大小为A4
         Document document = new Document(PageSize.A4);
         // 设置要输出到磁盘上的文件名称
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         RtfWriter2 writer = RtfWriter2.getInstance(document, bos);
         // 打开文档开始写内容
         document.open();
         // 创建一个N列的表格控件  
         Table wordTable = new Table(maxcol);
         // 设置表格占占页面宽度比例  
         wordTable.setWidth(100);
         wordTable.setAlignment(Element.ALIGN_CENTER); // 居中  
         wordTable.setAlignment(Element.ALIGN_MIDDLE); // 垂直居中  
         wordTable.setAutoFillEmptyCells(true); // 自动填满  
         wordTable.setCellsFitPage(true);
         // 中文采用Windows系统字体，幼圆常规字体
         BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);  
         com.lowagie.text.Font titleFont = new com.lowagie.text.Font(baseFont,10,com.lowagie.text.Font.BOLD);
         com.lowagie.text.Font font = new com.lowagie.text.Font(baseFont,8,com.lowagie.text.Font.NORMAL);
         // 创建一个表格的标题  
         Cell CellTitle = new Cell(new Phrase(fileName, titleFont));
         CellTitle.setColspan(maxcol);
         CellTitle.setBorder(Cell.NO_BORDER);
         CellTitle.setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
         CellTitle.setVerticalAlignment(Element.ALIGN_MIDDLE);  //垂直居中
         wordTable.addCell(CellTitle);
         // 创建一个表格的表头单元格  
         Cell wordTableHeaderCell = new Cell();
         // 设置表头样式
         wordHeadStyle(wordTableHeaderCell);
         // 获得头内容
         getWordTrendsHeader(headTableData, wordTable, wordTableHeaderCell, font, maxcol);
         // 获取映射对应的字段名
         List<String> fieldPropertyList = ArrayUtils.stringToList(headerProp);
         // 遍历集合数据，产生数据行
         for (int index = 0; index < list.size(); index++) {
             Map<String, Object> map = list.get(index);
             for (int i = 0; i <= fieldPropertyList.size(); i++) {
                 // 判断值的类型后进行强制类型转换
                 Object value = null;
                 String textValue = null;
                 if (i == 0) {
                     value = (index + 1) + "";
                 } else {
                     String fieldName = fieldPropertyList.get(i - 1);
                     value = map.get(fieldName.replaceAll("\"", ""));
                 }
                 if (value instanceof Boolean) {
                     boolean bValue = (Boolean) value;
                     textValue = "是";
                     if (!bValue) {
                         textValue = "不是";
                     }
                 } else if (value instanceof Date) {
                     Date date = (Date) value;
                     SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                     textValue = sdf.format(date);
                 } else if (value instanceof byte[]) {
                     // 有图片时，设置行高为60px;
//                     row.setHeightInPoints(60);
//                     // 设置图片所在列宽度为80px,注意这里单位的一个换算
//                     sheet.setColumnWidth(i, (short) (35 * 80));
//                     // sheet.autoSizeColumn(i);
//                     byte[] bsValue = (byte[]) value;
//                     HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index);
//                     anchor.setAnchorType(2);
//                     patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
                 } else if (value != null) {
                     // 其它数据类型都当作字符串简单处理
                     if (parseDate(value.toString())) { // 判断字符串是否为时间格式
                         SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                         Date date = null;
                         try {
                             date = sdf.parse(value.toString());
                         } catch (ParseException e) {
                             e.printStackTrace();
                         }
                         textValue = sdf.format(date);
                     } else {
                         textValue = value.toString();
                     }
                 }
                 Cell cell = new Cell(new Phrase(textValue, font));
                 cell.setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
                 cell.setVerticalAlignment(Element.ALIGN_MIDDLE);  //垂直居中
                 wordTable.addCell(cell);
             }
         }
         document.add(wordTable);
         document.close();
         writer.close();
         
         byte[] bytes = {};
         try {
             bytes = bos.toByteArray();
             bos.close(); 
         } catch (IOException e) {
             e.printStackTrace();
         }
         return bytes;
     }
	
	public static boolean parseDate(String value) {
		// 设置日期转化成功标识
		boolean dateflag = true;
		// 这里要捕获一下异常信息
		try {
			DateUtils.parseDate(value.toString(), parsePatterns);
		} catch (Exception e) {
			dateflag = false;
		}
		// 成功：true ;失败:false
		return dateflag;
	}
}
